package com.web.ShoppingDemo.util;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.web.ShoppingDemo.model.FileImage;
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
	//从public.properties中将配置的文件目录进行注入
	@Value("#{prop.basePath+prop.filePath}")
	private String filePath;
	
	//1.通过文件名获取拓展名
	private String getFileExt(String fileName){
		return FilenameUtils.getExtension(fileName);
	}
	//2.生成UUID随机数,作为新的文件名
	private String newFileName(String fileName){
		String ext = getFileExt(fileName);
		return UUID.randomUUID().toString()+"."+ext;
	}
	//3.实现文件上传的功能,返回新的文件名称
	/* (non-Javadoc)
	 * @see com.web.ShoppingDemo.util.FileUpload#uploadFile(com.web.ShoppingDemo.model.FileImage)
	 */
	@Override
	public String uploadFile(FileImage fileImage){
		//获取新的文件名
		String pic = newFileName(fileImage.getFilename());
		try {
			FileUtil.copyFile(fileImage.getFile(), new File(filePath,pic));
			return pic;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally{
			fileImage.getFile().delete();
		}
	}
}
